package com.example.springbootdemo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

@Configuration
public class RestTemplateConfig {
    //连接超时时间,当配置文件没设定时间时，默认6000ms
    @Value("${resttemplate.parameter.connectTimeout:6000}")
    private Integer connectTimeout;

    //读取超时时间,当配置文件没设定时间时，默认6000ms
    @Value("${resttemplate.parameter.readTimeout:6000}")
    private Integer readTimeout;

    @Bean
    public RestTemplate getRestTemplate() throws NoSuchAlgorithmException, KeyManagementException {
        // 创建信任所有证书的 SSLContext，并设置为默认 SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }}, null);
        SSLContext.setDefault(sslContext);

        // 创建可以忽略证书认证的 SimpleClientHttpRequestFactory
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory() {
            @Override
            protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
                if (connection instanceof HttpsURLConnection) {
                    ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
                    ((HttpsURLConnection) connection).setHostnameVerifier((hostname, session) -> true);
                }
                super.prepareConnection(connection, httpMethod);
            }
        };
        // 设置连接超时和读取超时（单位：毫秒）
        requestFactory.setConnectTimeout(connectTimeout);
        requestFactory.setReadTimeout(readTimeout);

        // 创建 RestTemplate，并设置 SimpleClientHttpRequestFactory
        // return new RestTemplate();
        return new RestTemplate(requestFactory);
    }


}
